<!DOCTYPE  HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
	<head>
		<title></title>
		<script type="text/javascript" src="../js/jquery.js"></script>
		<script type="text/javascript" src="data.js"></script>
		<script type="text/javascript">
			var appkey = "06aae299c62b24ab1400a7cd52816e01";
			var curIndex = 0;

			function fetchResult() {
				$("#process")[0].innerHTML = curIndex;
				if(curIndex >= arr.length) {
					alert("FETCH DONE!");
					return;
				}

				var mem = window.localStorage[ids[curIndex]];
				if(mem == null) {
					$.getJSON("http://api.douban.com/book/subjects?apikey=" + appkey + "&alt=json&q=" + arr[curIndex], function(data) {
						console.log(data);
						window.result = data;

						var entries = result.entry;
						if(entries.length > 0) {
							/*
							 category: Object
							 db:attribute: Array[4]
							 0: Object
							 1: Object
							 2: Object
							 3: Object
							 length: 4
							 __proto__: Array[0]
							 gd:rating: Object
							 @average: "7.7"
							 @max: 10
							 @min: 0
							 @numRaters: 18
							 __proto__: Object
							 id: Object
							 $t: "http://api.douban.com/book/subject/3583516"
							 __proto__: Object
							 link: Array[3]
							 title: Object
							 $t: "羊皮卷"
							 * */
							var entry = entries[0];
							var avg = entry["gd:rating"]["@average"];
							if(avg == 0 && entries.length > 1) {
								entry = entries[1];
								avg = entry["gd:rating"]["@average"];
							}

							window.localStorage[ids[curIndex]] = entry["gd:rating"]["@average"] + "|" + entry["title"]["$t"];
						} else {
							window.localStorage[ids[curIndex]] = 0;
						}
						curIndex++;
						fetchResult();
					});
				} else {
					curIndex++;
					fetchResult();
				}
			}

			function showResult() {
				for(var i = 0, l = window.localStorage, size = l.length; i < size; ++i) {
					var key = l.key(i);
					var value = l[key];
					var args = (value.indexOf("|") != -1) ? value.split("|") : ["", ""];
					document.writeln(key + "\t" + args[0] + "\t" + args[1] + "<br/>");
				}
			}

			function clearResult() {
				window.localStorage.clear();
				alert("CLEAR DONE!");
			}
		</script>
	</head>
	<body>
		<button onclick="fetchResult()">
			FETCH
		</button>
		<button onclick="showResult()">
			SHOW
		</button>
		<button onclick="clearResult()">
			RESET
		</button>
		<br/>
		<p id="process"> </p>
	</body>
</html>
